package manage.controller;

import manage.vo.LoginEntity;
import net.lcheng.commons.utils.ParseMD5;
import net.lcheng.model.SysUsers;
import net.lcheng.service.SysUsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;

/**
 * Created by qiliping on 15/12/1.
 * 登录Controller
 */
@Controller
public class LoginController {
    @Autowired
    private SysUsersService sysUsersService;

    /**
     * 登录GET
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String Index(Model model) {
        if (!model.containsAttribute("LoginEntity")) {
            model.addAttribute("LoginEntity", new LoginEntity());
        }
        return "login";
    }


    /***
     * 用户登陆
     * <p>注解配置，只允许POST提交到该方法
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Model model, @Valid @ModelAttribute("LoginEntity") LoginEntity user, BindingResult result) {
        if (result.hasErrors()) {
            return "login";
        }
        SysUsers userModel = sysUsersService.getUserByUsername(user.getUsername());

        if (userModel != null) {
            String inputPwd = ParseMD5.parseStrToMd5L32(user.getPassword());
            if (!userModel.getPassword().equals(inputPwd)) {
                model.addAttribute("error", "登录密码错误");
                return "login";
            }
            if (userModel.getStatus() != 1) {
                model.addAttribute("error", "无效的用户");
                return "login";
            }
        } else {
            model.addAttribute("error", "用户不存在");
            return "login";
        }
        //登录成功
        SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
        return "redirect:/main";

    }

    /***
     * 退出
     * @param model
     * @return
     */
    @RequestMapping(value = "logout")
    public String logout(Model model) {

        SecurityUtils.getSubject().logout();

        return "redirect:/main";

    }

    /***
     * 验证参数是否为空
     *
     * @param params
     * @return
     */
    private boolean checkParams(String[] params) {
        for (String param : params) {
            if (param == "" || param == null || param.isEmpty()) {
                return false;
            }
        }
        return true;
    }
}
